package com.yunshipei.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.webkit.JavascriptInterface;

import com.bumptech.glide.Glide;
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader;
import com.bumptech.glide.load.model.GlideUrl;
import com.yunshipei.base.BaseLoginActivity;
import com.yunshipei.common.Globals;
import com.yunshipei.common.LoginManager;
import com.yunshipei.common.ProfileHandler;
import com.yunshipei.common.manager.EnterConfig;
import com.yunshipei.common.net.HttpMethods;
import com.yunshipei.core.manager.XCloudSDKManager;
import com.yunshipei.core.net.EnterClient;
import com.yunshipei.core.utils.FileUtils;
import com.yunshipei.enterplorer.R;
import com.yunshipei.manager.YspPreferences;
import com.yunshipei.model.MainExtraBean;
import com.yunshipei.ui.dialog.DialogHelper;
import com.yunshipei.ui.dialog.WaitDialog;
import com.yunshipei.ui.view.H5WebView;
import com.yunshipei.utils.BaseUtil;
import com.yunshipei.utils.EncUtils;
import com.yunshipei.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.InputStream;

import butterknife.Bind;
import butterknife.ButterKnife;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class H5LoginActivity extends BaseLoginActivity {


    @Bind(R.id.web_view_login)
    protected H5WebView mWebView;

    private LoginManager mLoginManager;
    private SharedPreferences mPreferences;
    private String mManagerServer;
    private String mCompanyID;
    private String mCompanyLogo;
    private String mPlaceHolder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_h5_login);
        ButterKnife.bind(this);
        mPreferences = YspPreferences.getInstance().getSharedPreferences();
        SharedPreferences preferences = getSharedPreferences(Globals.NO_CLEAR_SHP, MODE_PRIVATE);
        mManagerServer = preferences.getString(Globals.MANUAL_BASE_URL, "");
        mCompanyID = preferences.getString(Globals.SP_COMPANY_ID, "");
        mCompanyLogo = preferences.getString(Globals.SP_COMPANY_LOGO, "");
        mPlaceHolder = preferences.getString(Globals.SP_COMPANY_PLACE_HOLDER, getResources().getString(R.string.txt_input_account));
        if (TextUtils.isEmpty(mManagerServer)) {
            mManagerServer = preferences.getString(Globals.SP_HUB_GET_SERVER, "");
        }
        if (TextUtils.isEmpty(mManagerServer) || TextUtils.isEmpty(mCompanyID)) {
            startActivity(new Intent(this, CompanyNameLoginActivity.class));
            finish();
        } else {
            mLoginManager = new LoginManager(this);
            HttpMethods.getInstance().initManagerServer(mManagerServer);
            OkHttpUrlLoader.Factory factory = new OkHttpUrlLoader.Factory(EnterClient.getInstances().getManagerClient());
            Glide.get(this).register(GlideUrl.class, InputStream.class, factory);
            String code = getSharedPreferences(Globals.NO_CLEAR_SHP, MODE_PRIVATE).getString(Globals.SP_COMPANY_THEME_CODE, "1");
            EnterConfig.getInstance().setThemeCode(code);
            //加载h5页面
            mWebView.addJavascriptInterface(object, "redcore");
            SharedPreferences sp = getSharedPreferences(ProfileHandler.H5_PKG_CONFIG, MODE_PRIVATE);
            int saveVersion = sp.getInt(ProfileHandler.H5_LOGIN_PAGE_VERSION, 0);
            int selfVersion = 0;
            String resJSON = FileUtils.readAssertResource(this, "local/localResCfg.json");
            try {
                JSONObject localCfgObject = new JSONObject(resJSON);
                selfVersion = localCfgObject.optInt("loginpage", 0);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            String loadUrl = "";
            File file = new File(getFilesDir().getParent() + File.separator + "web_login" + File.separator + "index.html");
            if (saveVersion > selfVersion && file.exists()) {
                loadUrl = "file://" + file.getPath();
            } else {
                loadUrl = "file:///android_asset/local/loginpage/index.html";
            }
            mWebView.loadUrl(loadUrl);
        }
    }

    private WaitDialog mWaitingDialog;

    private void userLogin(final String userName, final String password) {
        if (mWaitingDialog == null) {
            mWaitingDialog = DialogHelper.getNoCancelableWaitDialog(this, getString(R.string.login_loading_message));
        }
        mWaitingDialog.show();
        mLoginManager.createLoginFlowable(userName, password).map(new Function<MainExtraBean, MainExtraBean>() {
            @SuppressLint({"CommitPrefEdits", "ApplySharedPref"})
            @Override
            public MainExtraBean apply(MainExtraBean mainExtraBean) throws Exception {
                String uuid = mainExtraBean.getUserInfo().getUuid();
                mPreferences.edit().putString(Globals.USER_NAME, userName).putString(Globals.PASSWORD, EncUtils.encrypt(uuid, password.getBytes())).putBoolean(Globals.SP_MULTI_DEVICES, false).commit();
                getSharedPreferences(Globals.NO_CLEAR_SHP, MODE_PRIVATE).edit().putString(Globals.SP_COMPANY_THEME_CODE, mainExtraBean.getThemeCode()).commit();
                EnterConfig.getInstance().setThemeCode(mainExtraBean.getThemeCode());
                HttpMethods.getInstance().initManagerServer(mManagerServer); //因为登录的时候client被重置了
                return mainExtraBean;
            }
        }).subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<MainExtraBean>() {
            @Override
            public void accept(MainExtraBean mainExtraBean) throws Exception {
                startActivity(new MainActivity.MainIntentBuilder(H5LoginActivity.this).setData(mainExtraBean).isAutoLogin(false).getIntent());
                mWaitingDialog.dismiss();
                finish();
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                mWaitingDialog.dismiss();
                ToastUtils.showToast(XCloudSDKManager.getInstance().generateError(throwable));
            }
        });
    }

    private Object object = new Object() {

        @JavascriptInterface
        public String companyInfo() {
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("managerServer", mManagerServer);
                jsonObject.put("companyId", mCompanyID);
                jsonObject.put("themeColor", EnterConfig.getInstance().optGlobalColor());
                jsonObject.put("accountPlaceHolder", mPlaceHolder);
                jsonObject.put("logoUrl", mCompanyLogo);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return jsonObject.toString();
        }

        @JavascriptInterface
        public void login(final String userName, final String password) {
            AndroidSchedulers.mainThread().createWorker().schedule(new Runnable() {
                @Override
                public void run() {
                    userLogin(userName, password);
                }
            });
        }

        @JavascriptInterface
        public void backToEnterCodePage() {
            BaseUtil.hideKeyBoard(H5LoginActivity.this);
            mPreferences.edit().putString(Globals.USER_NAME, "").putString(Globals.PASSWORD, "").apply();
            startActivity(new Intent(H5LoginActivity.this, CompanyNameLoginActivity.class));
            finish();
        }

        @JavascriptInterface
        public String validateVerifyCode(String serverCode, String inputCode) {
            int state = 0;
            String subCode = BaseUtil.makeAuthString(serverCode);
            if (!TextUtils.isEmpty(subCode) && !TextUtils.isEmpty(inputCode) && inputCode.equals(subCode)) {
                state = 1;
            }
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("state", state);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return jsonObject.toString();
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mWebView != null){
            mWebView.destroy();
            mWebView = null;
        }
    }
}
